<?php

namespace app\admin\controller;

use think\facade\Db;
use think\facade\Session;
use utils\Sort;
use think\facade\View;
use app\common\controller\CommonController;

abstract class AdminBase extends CommonController
{
    final public function initialize()
    {
        if (isset($this->app->user)){
            $menuList = Session::get('menuList');
            if (empty($menuList)){
                $menus = Db::query("select m.menu_id,m.menu_name,m.menu_path,m.menu_pid,m.menu_sort from t_user_role ur join t_menu_role mr on mr.role_id = ur.role_id join t_menu m on m.menu_id = mr.menu_id where uid = {$this->app->user->uid}");
                $menus1 = Db::query('select m.menu_id,m.menu_name,m.menu_path,m.menu_pid,m.menu_sort from t_menu m left join t_menu_role mr on m.menu_id = mr.menu_id where mr.menu_id is null;');
                $menuList = array_merge($menus1, $menus);
                $menuList = self::combineMenu($menuList);
                $menuList = Sort::array_sort($menuList, 'menu_sort');
                Session::set('menuList', $menuList);
            }
            View::assign('menuList', $menuList);
            View::assign('user', $this->app->user);
        }
    }

    Static Public function combineCate($cate, $pid=0, $level=0, $html='--- '){
        $lists = [];
        if (is_array($cate)) {
            foreach ($cate as $v) {
                if ($v['cate_pid'] == $pid) {//判断栏目pid是否与形参$pid相等
                    $v['cate_depth'] = $level+1;
                    $v['html'] = str_repeat($html, $level);
                    $lists[] = $v;
                    $lists = array_merge($lists, self::combineCate($cate,$v['cate_id'], $v['cate_depth']));
                }
            }
        }

        return $lists;
    }

    Static Public function combineMenu($menu, $pid=0, $level=0, $html='--- '){
        $lists = [];
        if (is_array($menu)) {
            foreach ($menu as $v) {
                if ($v['menu_pid'] == $pid) {//判断栏目pid是否与形参$pid相等
                    $v['menu_depth'] = $level+1;
                    $v['html'] = str_repeat($html, $level);
                    $lists[] = $v;
                    $lists = array_merge($lists, self::combineMenu($menu,$v['menu_id'], $v['menu_depth']));
                }
            }
        }
        return $lists;
    }
}